package com.geekhale.validate.support;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.validation.Errors;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.Validator;

import java.util.HashMap;
import java.util.List;

public class MethodValidateInterceptor implements MethodInterceptor {
    private final List<Validator> validators;

    public MethodValidateInterceptor(List<Validator> validators) {
        this.validators = validators;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        Errors errors = new MapBindingResult(new HashMap<>(), "test");
        for (Object param : arguments){
            validateFor(param, errors);
        }
        return invocation.proceed();
    }

    private void validateFor(Object param, Errors errors) {
        if (param == null){
            return;
        }
        this.validators.stream()
                .filter(validator -> validator.supports(param.getClass()))
                .forEach(validator -> validator.validate(param, errors));
    }
}
